//
// Created by xqyr on 2025/4/11.
//


#include "beep.h"
#include "log/log.h"

Beep::Beep(std::function<void(const bool)> fun):
        CharDeviceAPP("/dev/beepgpio") {
    set_devChangeCallback(std::bind(&Beep::devChangeCallback,this,std::placeholders::_1));
    set_beepStatusChangeCallback(fun);
    setBeep(beepStatus);
}

void Beep::setBeep(bool flag) {
    if(!writeDev(&flag, 1))
        beepStatus = flag;
    else
        beepStatus = BEEP_OFF;
    if(beepStatusChangeCallback) {
        beepStatusChangeCallback(flag);
    }
}

bool Beep::getBeep() {
    auto temp = beepStatus;
    auto err = readDev(&beepStatus, 1);
    if(  err < 0){
        LOG_WARN("readDev error = %d",err);

        setBeep(BEEP_OFF);
    }
    if(temp != beepStatus){
        setBeep(beepStatus);
    }
    return beepStatus;
}

void Beep::devChangeCallback(const bool) {
    LOG_INFO("beep open status : %d",getdevStatus());
}

void Beep::set_beepStatusChangeCallback(std::function<void(const bool)> fun) {
    beepStatusChangeCallback = fun;
    if(beepStatusChangeCallback) {
        beepStatusChangeCallback(getBeep());
    }
}
